package com.zyx.flink.realtime.utils;

import com.alibaba.fastjson.JSONObject;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;

import javax.sql.DataSource;
import java.sql.*;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import static com.zyx.flink.realtime.cons.PhoenixConst.HABSE_SCHEMA;
import static com.zyx.flink.realtime.cons.PhoenixConst.PHOENIX_URL;

/**
 * @author zyx
 * @since 2021/6/11 19:40
 * desc: 从Phoenix中查询数据
 */
@Slf4j
public class HikariPhoenixUtil {

    private static DataSource dataSource;

    static {
        try {
            Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (dataSource == null) {
            synchronized (HikariPhoenixUtil.class) {
                if (dataSource == null) {
                    HikariConfig config = new HikariConfig();
                    config.setJdbcUrl(PHOENIX_URL);
                    config.setDriverClassName("org.apache.phoenix.jdbc.PhoenixDriver");
                    // 连接超时：30秒
                    config.setConnectionTimeout(TimeUnit.SECONDS.toMillis(30L));
                    // 空闲超时：180秒
                    config.setIdleTimeout(TimeUnit.SECONDS.toMillis(180L));
                    // 最大连接数：5
                    config.setMaximumPoolSize(5);
                    Properties prop = new Properties();
                    prop.setProperty("schema", HABSE_SCHEMA);
                    prop.setProperty("phoenix.schema.isNamespaceMappingEnabled", String.valueOf(true));
                    prop.setProperty("phoenix.schema.mapSystemTablesToNamespace", String.valueOf(true));
                    config.setDataSourceProperties(prop);
                    dataSource = new HikariDataSource(config);
                    System.out.println("创建Hikari连接池");
                }
            }
        }
    }

    public static Connection getPhoenixConn() {
        if (dataSource == null) {
            synchronized (HikariPhoenixUtil.class) {
                if (dataSource == null) {
                    HikariConfig config = new HikariConfig();
                    config.setJdbcUrl(PHOENIX_URL);
                    config.setDriverClassName("org.apache.phoenix.jdbc.PhoenixDriver");
                    // 连接超时：30秒
                    config.setConnectionTimeout(TimeUnit.SECONDS.toMillis(30L));
                    // 空闲超时：180秒
                    config.setIdleTimeout(TimeUnit.SECONDS.toMillis(180L));
                    // 最大连接数：5
                    config.setMaximumPoolSize(5);
                    Properties prop = new Properties();
                    prop.setProperty("schema", HABSE_SCHEMA);
                    prop.setProperty("phoenix.schema.isNamespaceMappingEnabled", String.valueOf(true));
                    prop.setProperty("phoenix.schema.mapSystemTablesToNamespace", String.valueOf(true));
                    config.setDataSourceProperties(prop);
                    dataSource = new HikariDataSource(config);
                    System.out.println("创建Hikari连接池");
                }
            }
        }
        try {
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    /**
     * 从Phoenix中查询数据
     * @param sql 查询的sql语句
     * @param clazz 返回类型
     * @param <T> 返回值类型的泛型
     * @return 返回值
     */
    public static <T> List<T> queryList(String sql, Class<T> clazz) {
        Connection conn = getPhoenixConn();
        List<T> resultList = new ArrayList<>();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //获取数据库操作对象
            if (conn == null) {
                log.error("++++++++++++++++++++未获取Phoenix的连接");
            } else {
                ps = conn.prepareStatement(sql);
                rs = ps.executeQuery();
                //通过结果集对象获取元数据信息
                ResultSetMetaData metaData = rs.getMetaData();
                //处理结果集
                while (rs.next()) {
                    //声明一个对象，用于封装查询的一条结果集
                    T rowData = clazz.newInstance();
                    for (int i = 1; i <= metaData.getColumnCount(); i++) {
                        BeanUtils.setProperty(rowData, metaData.getColumnName(i), rs.getObject(i));
                    }
                    resultList.add(rowData);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("从维度表中查询数据失败");
        } finally {
            //释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultList;
    }

    /*public static void main(String[] args) throws SQLException {
        for (int i = 0; i < 5; i++) {
            System.out.println("第" + i + "次开始时间:" + Instant.now());
            // System.out.println(queryList("select * from \"dbtest\".\"user\"", JSONObject.class));
            System.out.println(queryList("select * from user_info where id = '1001'", JSONObject.class));
            System.out.println("第" + i + "次结束时间:"+ Instant.now());
        }
    }*/
}
